package cm.tl.pms.annotation;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Slf4j
@Aspect
@Component
public class RuntimeLogProcessor {

    @Around("@annotation(RuntimeLog)")
    public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object proceed;
        String className = joinPoint.getTarget().getClass().getSimpleName();
        String methodName = joinPoint.getSignature().getName();
        try {
            String methodArgs = JSONUtil.toJsonStr(joinPoint.getArgs());
            log.info("类名.方法名: {}.{} 参数: {}", className, methodName, methodArgs);
            proceed = joinPoint.proceed();
            long executionTime = System.currentTimeMillis() - startTime;
            log.info("类名.方法名: {}.{} 执行时间 = {} ms", className, methodName, executionTime);
        } catch (Throwable throwable) {
            long executionTime = System.currentTimeMillis() - startTime;
            log.error("Method: {}.{} 执行异常，执行时间 = {} ms", className, methodName, executionTime, throwable);
            throw throwable;
        }
        return proceed;
    }
}